<script setup lang="ts">
import { dayjs } from 'element-plus'
import { useLoadData, checkEnterpriseInfo, type ListItem, type SaveFnParams } from './composable'
import { REPORT_ACTION, REPORT_FORM_ID, REPORT_STATUS, REPORT_STATUS_TEXT } from '@/enum'

import ReportComponent from './components/ReportComponent.vue'
import type { SaveParams } from '@/components/Reports/type'
import ReportRecordsModal from './components/ReportRecordsModal.vue'

import useReportStore from '@/store/modules/reportStore'

const modalRef = ref<InstanceType<typeof ReportRecordsModal>>()
const enterpriseLists = shallowRef<{
  [key: string]: any
  label: string
  value: string
}[]>([])
const socialCreditCode = ref('')
const tenantName = ref('')
const tenantRegion = ref('')
const subsidiaryType = ref(0)
const sortNumber = ref(0)
const month = ref(dayjs().subtract(1, 'month').format('YYYY-MM'))
const status = ref<REPORT_STATUS>()
const statusList = shallowRef<{
  [key: string]: any
  label: string
  value: REPORT_STATUS
}[]>([
  { label: REPORT_STATUS_TEXT.UNDER_REPORT, value: REPORT_STATUS.UNDER_REPORT },
  { label: REPORT_STATUS_TEXT.STAGED, value: REPORT_STATUS.STAGED },
  { label: REPORT_STATUS_TEXT.REPORTED, value: REPORT_STATUS.REPORTED },
  { label: REPORT_STATUS_TEXT.RESOLVED, value: REPORT_STATUS.RESOLVED },
  { label: REPORT_STATUS_TEXT.REJECTED, value: REPORT_STATUS.REJECTED },
])
const visible = ref(false)
const userStore = useUserStore()
const reportStore = useReportStore()

const {
  loading,
  tableData,
  queryList,
  getStatusText,
  showAction,
  getEnterpriseListOfReport,
  report,
  exportFile,
  getTagColor,
} = useLoadData()

const router = useRouter()
const currentRow = ref<ListItem>()
const currentAction = ref<REPORT_ACTION>()
const title = computed(() => {
  return `${unref(tenantName) ?? ''} - ${unref(currentRow)?.name ?? ''}`
})
const needCheckEnterprise = ref(false)

// 手动改为只读
const forceReadonly = ref(false)

const showReportOrSaveButton = computed(() => {
  if (unref(forceReadonly))
    return false

  const c = unref(currentRow)
  // 只有在未填写、已填写、退回状态时显示保存按钮
  return c
    ? [
        REPORT_STATUS.UNDER_REPORT,
        REPORT_STATUS.STAGED,
        REPORT_STATUS.REJECTED,
      ].includes(c.status)
    : false
})

const readonly = computed(() => {
  if (unref(forceReadonly))
    return true
  // 填报模式下，如果报表的状态是已上报或已审核时，只读
  const c = unref(currentRow)
  if (c) {
    return [REPORT_STATUS.REPORTED, REPORT_STATUS.RESOLVED].includes(c.status)
  }
  return false
})

async function doAction(list: ListItem, action: REPORT_ACTION) {
  // 复位
  forceReadonly.value = false
  currentRow.value = list
  currentAction.value = action

  reportStore.setRow(list)

  // 查看只读
  if (REPORT_ACTION.DO_VIEW === action) {
    forceReadonly.value = true
  }

  await nextTick()
  if ([REPORT_ACTION.DO_VIEW, REPORT_ACTION.DO_MODIFY, REPORT_ACTION.DO_FILL].includes(action)) {
    visible.value = true
  }
  // 上报
  if (REPORT_ACTION.DO_REPORT === action) {
    if (list.id) {
      report(list.id).then(() => {
        ElMessage.success('上报成功')
        clickSearch()
      })
    }
  }

  // 导出
  if (REPORT_ACTION.DO_EXPORT === action) {
    if (list.id)
      exportFile(list.id)
  }

  // 历史操作
  if (REPORT_ACTION.DO_LOG === action) {
    modalRef.value?.open()
  }
}

function enterpriseChange(code: string) {
  const target = enterpriseLists.value.find(v => v.value === code)
  tenantName.value = target?.label ?? ''
  tenantRegion.value = target?.region ?? ''
  subsidiaryType.value = target?.subsidiaryType
  sortNumber.value = target?.sortNumber
}

async function clickSearch() {
  if (!unref(month)) {
    ElMessage.warning('请选择报告期')
    return
  }
  if (unref(socialCreditCode)) {
    queryList({
      time: unref(month),
      socialCreditCode: unref(socialCreditCode),
      subsidiaryType: unref(subsidiaryType),
      // 煤矿
      type: '0,3',
      status: unref(status),
    })
  }
  else {
    ElMessage.warning('请先在数据字典菜单中配置数据上报企业')
  }
}

async function clickSave(triggerSave: (params: SaveParams) => any, saveType: 0 | 1) {
  // console.log(getData())
  triggerSave({
    saveType,
    beforeSaveFn: (reportId, formId, params) => {
      if (!params.socialCreditCode) {
        params.socialCreditCode = socialCreditCode.value
      }
      if (!params.subsidiaryName) {
        params.subsidiaryName = tenantName.value
      }
      // 保存或更新都使用列表筛选条件下拉选中的所属区域
      params.subsidiaryRegion = tenantRegion.value

      // 洗煤厂标识
      params.subsidiaryType = subsidiaryType.value
      // 排序标识
      params.sortNumber = sortNumber.value

      if (!params.year) {
        params.year = Number(unref(month).split('-')[0])
      }
      if (!params.month) {
        params.month = Number(unref(month).split('-')[1])
      }
      // 如果currentRow的id存在，但是参数中params.id不存在
      // 说明已经做了新增操作，当前正在做更新操作
      if (currentRow.value?.id && !params.id) {
        params.id = currentRow.value.id
      }
      // 新增 userName 字段
      if (!params.userName) {
        params.userName = userStore.userInfo.userName
      }
      return new Promise((resolve) => {
        // 主要耗能设备表在保存并上报时
        // 给出“上报会将所有耗能设备一并上报，是否确认上报？”确认提示
        if (
          saveType === 1
          && formId
          && [
            REPORT_FORM_ID.MAIN_VENTILATOR,
            REPORT_FORM_ID.MAIN_DRAINAGE,
            REPORT_FORM_ID.AIR_COMPRESSOR,
            REPORT_FORM_ID.MAIN_SHAFT_BELT,
            REPORT_FORM_ID.COMBINED_MINING_PRODUCTION,
            REPORT_FORM_ID.TUNNELING_PRODUCTION,
          ].includes(formId)
        ) {
          ElMessageBox.confirm('上报会将所有耗能设备一并上报，是否确认上报？')
            .then(() => {
              resolve(true)
            }).catch(() => {
              resolve(false)
            })
        }
        else {
          resolve(true)
        }
      })
    },
    afterSaveFn: async (reportId, formId, data, responseId) => {
      ElMessage.success('操作成功')
      // 新增数据会返回id
      if (responseId && currentRow.value) {
        currentRow.value.id = responseId
      }
      // 主要耗能设备表在保存并上报后，其他相关表变为只读
      if (
        saveType === 1
        && formId
        && [
          REPORT_FORM_ID.MAIN_VENTILATOR,
          REPORT_FORM_ID.MAIN_DRAINAGE,
          REPORT_FORM_ID.AIR_COMPRESSOR,
          REPORT_FORM_ID.MAIN_SHAFT_BELT,
          REPORT_FORM_ID.COMBINED_MINING_PRODUCTION,
          REPORT_FORM_ID.TUNNELING_PRODUCTION,
        ].includes(formId)
      ) {
        forceReadonly.value = true
      }
      // 上报成功后返回列表页
      if (saveType === 1) {
        visible.value = false
        await nextTick()
        clickSearch()
      }
    },
  })
}

function whenTabBeforeLeave(saveFn: (o: SaveFnParams) => Promise<boolean>) {
  return new Promise<any>((resolve, reject) => {
    // console.log('reportStore row id: ', reportStore.row?.id)
    const obj = {
      socialCreditCode: socialCreditCode.value,
      subsidiaryName: tenantName.value,
      subsidiaryRegion: tenantRegion.value,
      year: Number(unref(month).split('-')[0]),
      month: Number(unref(month).split('-')[1]),
      id: reportStore.row?.id,
      userName: userStore.userInfo.userName,
    } as SaveFnParams
    saveFn(obj).then((res) => {
      resolve(res)
    }).catch((e) => {
      reject(e)
    })
  })
}

async function clickExport() {
  const c = unref(currentRow)
  if (c && c.id) {
    exportFile(c.id)
  }
}

async function clickBack() {
  visible.value = false
  await nextTick()
  clickSearch()
}

async function callback() {
  const d = await getEnterpriseListOfReport()
  if (d === null || !d.length) {
    if (!unref(needCheckEnterprise)) {
      return ElMessage.warning('请先在数据字典菜单中配置数据上报企业')
    }
    // 没有配置企业
    // 检查当前企业信息
    // 企业信息完善则查询当前企业的数据填报列表
    const s = await checkEnterpriseInfo(userStore.userInfo, () => {
      router.push({
        path: '/enterprise-information',
      })
    })
    if (s) {
      // 从企业基本信息中拿
      socialCreditCode.value = s.socialCreditCode
      tenantName.value = s.enterpriseName
      tenantRegion.value = s.districtBelong
      subsidiaryType.value = (s as any).subsidiaryType || null
      sortNumber.value = (s as any).sortNumber || null
      await nextTick()
      clickSearch()
    }
  }
  else {
    // 配置了企业下拉数据
    enterpriseLists.value = d.map((v: any) => ({
      ...v,
      label: v.name,
      value: v.socialCreditCode,
    }))
    // 从字典的配置中拿
    socialCreditCode.value = d[0].socialCreditCode
    tenantName.value = d[0].name
    tenantRegion.value = d[0].region
    subsidiaryType.value = d[0].subsidiaryType
    sortNumber.value = d[0].sortNumber
    await nextTick()
    clickSearch()
  }
}

// onActivated(callback)
onMounted(callback)
</script>

<template>
  <div class="relative h-full w-full flex flex-col p-4">
    <div class="fs-14 flex items-center gap-3">
      <span>报告期：</span>
      <ElDatePicker v-model="month" :clearable="false" :editable="false" type="month" placeholder="请选择月份" value-format="YYYY-MM" format="YYYY-MM" />
      <template v-if="enterpriseLists && enterpriseLists.length">
        <span>企业：</span>
        <ElSelect v-model="socialCreditCode" class="!w-60" @change="enterpriseChange">
          <ElOption v-for="item in enterpriseLists" :key="item.value" :label="item.label" :value="item.value" />
        </ElSelect>
      </template>
      <span>状态：</span>
      <ElSelect v-model="status" class="!w-60" clearable filterable>
        <ElOption v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
      </ElSelect>
      <SearchButton @click="clickSearch" />
    </div>
    <ElTable
      v-loading="loading" :data="tableData"
      height="100%" class="alpha-block mt-4 !border-0"
      element-loading-custom-class="global-loading"
    >
      <template #empty>
        <TableEmpty />
      </template>
      <ElTableColumn label="报表名称" prop="name" />
      <ElTableColumn label="状态" prop="status">
        <template #default="scope">
          <span class="fs-12" :style="{ color: getTagColor(scope.row.status) }">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="备注" prop="remark" />
      <ElTableColumn label="操作" :width="340">
        <template #default="scope">
          <ElButton
            v-if="showAction(scope.row.status, 3)"
            type="primary"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_VIEW)"
          >
            查看
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 1)"
            type="primary"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_FILL)"
          >
            填写
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 2)"
            type="warning"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_MODIFY)"
          >
            修改
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 4)"
            type="danger"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_REPORT)"
          >
            上报
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 5)"
            type="info"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_LOG)"
          >
            历史操作
          </ElButton>
          <ElButton
            v-if="showAction(scope.row.status, 6)"
            type="success"
            size="small"
            @click="doAction(scope.row, REPORT_ACTION.DO_EXPORT)"
          >
            导出
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <FullscreenModal v-model="visible">
      <div v-if="visible" class="absolute inset-0 m-4 flex flex-col gap-4">
        <ElPageHeader class="flex-shrink-0 px-4 py-3" title="返回" content="煤矿填报" @back="clickBack" />
        <ReportComponent v-if="currentRow" :social-credit-code="socialCreditCode" :company="tenantName" :company-region="tenantRegion" :readonly="readonly" :data-id="reportStore.row?.id" :month="month" :title="title" :report-id="currentRow.tId" :when-tab-before-leave="whenTabBeforeLeave">
          <template #action="{ triggerSave }">
            <div v-if="showReportOrSaveButton" class="absolute right-0 top-1/2 flex items-center -translate-y-1/1">
              <ElButton type="primary" @click="clickSave(triggerSave, 0)">
                保存
              </ElButton>
              <ElButton type="danger" @click="clickSave(triggerSave, 1)">
                保存并上报
              </ElButton>
            </div>
            <div v-else class="absolute right-0 top-1/2 flex items-center -translate-y-1/1">
              <ElButton type="success" @click="clickExport">
                导出
              </ElButton>
            </div>
          </template>
        </ReportComponent>
      </div>
    </FullscreenModal>

    <ReportRecordsModal v-if="currentRow && currentRow.id" ref="modalRef" :data-id="currentRow?.id" :title="`${tenantName}-${currentRow.name}-` + `操作记录`" />
  </div>
</template>
